package com.numberone.iotplatform.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册一个 STOMP 端点，前端将连接到这个 URL
        // withSockJS() 提供 WebSocket 的后备选项
        registry.addEndpoint("/ws").setAllowedOrigins("http://localhost:3000").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 设置消息代理，用于路由消息
        // /topic 前缀的消息将被路由到消息代理（broker）
        registry.enableSimpleBroker("/topic");
        // /app 前缀的消息将被路由到应用后端的 @MessageMapping 方法
        registry.setApplicationDestinationPrefixes("/app");
    }
}